package com.ruoyi.web.controller.wokerSys;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.worker.constant.Constant;
import com.ruoyi.worker.domain.MonthlyAttendanceIni;
import com.ruoyi.worker.domain.workAttendance.AttendanceDailyRecord;
import com.ruoyi.worker.domain.workAttendance.AttendanceMonthRecord;
import com.ruoyi.worker.domain.workAttendance.AttendanceMonthSumRecord;
import com.ruoyi.worker.domain.workAttendance.AttendanceSumDailyRecord;
import com.ruoyi.worker.domain.workAttendance.vo.AttendanceMonthRecordDto;
import com.ruoyi.worker.domain.workAttendance.vo.AttendanceMonthRecordVo;
import com.ruoyi.worker.service.AttendanceSignService;
import com.ruoyi.worker.service.workerSys.WorkAttendanceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName WorkAttendance
 * @Description 长期工考勤
 * @Author leizhang
 * Date 2021/11/16 9:54 上午
 * @Version 1.0
 **/
@RestController
@RequestMapping("/workAttendanceApi")
@Slf4j
public class WorkAttendanceApi extends BaseController {

    @Resource
    private WorkAttendanceService workAttendanceService;
    @Resource
    private AttendanceSignService signService;

    /**
     * @param file
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @Description : 考勤记录保存
     * @Author : leizhang
     * @Date 4:45 下午 2021/11/19
     **/
    @PostMapping("/saveWorkAttendance")
    @Log(title = "考勤记录保存", businessType = BusinessType.INSERT)
    public AjaxResult saveWorkAttendanceInfo(@RequestParam("file") MultipartFile file) throws Exception {
        return workAttendanceService.saveAttendancePassRecord(file);
    }

    /**
     * @param requestParam
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @Description : 考勤记录生成
     * @Author : leizhang
     * @Date 4:06 下午 2021/11/21
     **/
    @PostMapping("/saveAttendanceRecord")
    @Log(title = "考勤记录生成", businessType = BusinessType.INSERT)
    public AjaxResult saveAttendanceRecord(@RequestBody Map<String, Object> requestParam) {
        try {
            workAttendanceService.saveWorkAttendanceInfo(requestParam);
            return AjaxResult.success();
        } catch (Exception e) {
            log.error("生成考勤数据错误:{}", e.getCause(), e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * @param attendanceSumDailyRecord
     * @return com.ruoyi.common.core.page.TableDataInfo
     * @Description : 考勤汇总记录查询
     * @Author : leizhang
     * @Date 4:08 下午 2021/11/21
     **/
    @GetMapping("/getAttendanceSumDailyRecord")
    @Log(title = "考勤汇总记录查询", businessType = BusinessType.INSERT)
    public TableDataInfo listOfAttendanceSumRecords(AttendanceSumDailyRecord attendanceSumDailyRecord) {
        startPage();
        List<AttendanceSumDailyRecord> attendanceSumDailyRecords = workAttendanceService.listOfAttendanceSumRecords(attendanceSumDailyRecord);
        return getDataTable(attendanceSumDailyRecords);
    }

    /**
     * @param attendanceDailyRecord
     * @return com.ruoyi.common.core.page.TableDataInfo
     * @Description : 考勤个人信息查询
     * @Author : leizhang
     * @Date 4:08 下午 2021/11/21
     **/
    @GetMapping("/getAttendanceRecord")
    @Log(title = "考勤个人信息查询", businessType = BusinessType.INSERT)
    public TableDataInfo listOfAttendanceRecord(AttendanceDailyRecord attendanceDailyRecord) {
        startPage();
        List<AttendanceDailyRecord> attendanceDailyRecords = workAttendanceService.listOfAttendanceRecord(attendanceDailyRecord);
        return getDataTable(attendanceDailyRecords);
    }

    /**
     * @param attendanceDailyRecord
     * @return com.ruoyi.common.core.page.TableDataInfo
     * @Description : 个人通行记录查询
     * @Author : leizhang
     * @Date 4:08 下午 2021/11/21
     **/
    @GetMapping("/getAttendancePassRecord")
    @Log(title = "个人通行记录查询", businessType = BusinessType.INSERT)
    public AjaxResult listOfAttendancePassRecord(@RequestParam Map<String, Object> attendanceDailyRecord) {
        List<MonthlyAttendanceIni> monthlyAttendanceInis = workAttendanceService.listOfMonthlyAttendanceIni(attendanceDailyRecord);
        return AjaxResult.success(monthlyAttendanceInis);
    }

    /**
     * @param file
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @Description : 考勤记录保存
     * @Author : leizhang
     * @Date 4:45 下午 2021/11/19
     **/
    @PostMapping("/updateWorkAttendance")
    @Log(title = "考勤记录导入修改", businessType = BusinessType.INSERT)
    public AjaxResult updateWorkAttendance(@RequestParam("file") MultipartFile file) throws Exception {
        workAttendanceService.updateAttendanceInfo(file);
        return AjaxResult.success();
    }

    /**
     * @param ids
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @Description : 导出个人考勤信息ByIds
     * @Author : leizhang
     * @Date 4:44 下午 2021/11/23
     **/
    @Log(title = "考勤信息导出ById", businessType = BusinessType.EXPORT)
    @GetMapping("/exportAttendance/{ids}")
    public AjaxResult exportAttendanceIngo(@PathVariable int[] ids) {
        List<AttendanceDailyRecord> attendanceDailyRecords = workAttendanceService.listOfAttendanceRecordByIds(ids);
        AttendanceDailyRecord attendanceDailyRecord = attendanceDailyRecords.get(Constant.NUMBER_0);
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName("考勤记录");
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, AttendanceDailyRecord.class, attendanceDailyRecords);
        String fileName = attendanceDailyRecord.getDeptName().concat(attendanceDailyRecord.getWorkTime()) + ".xlsx";
        OutputStream out = null;
        try {
            out = new FileOutputStream(getAbsoluteFile(fileName));
            workbook.write(out);
            return AjaxResult.success(fileName);
        } catch (Exception e) {
            log.error("excel输出错误信息:[{}]", e.getCause(), e);
            AjaxResult.error();
        } finally {
            IOUtils.closeQuietly(workbook);
            IOUtils.closeQuietly(out);
        }
        return AjaxResult.success();
    }

    /**
    * @author: 陈宇寰
    * @date: 2021-12-08 11:18:19
    * @params:
    * @return:
     * @type: 需求变更
    * @description: 由原来的勾选导出改为条件导出
    */
    @Log(title = "日考勤信息导出 with 条件", businessType = BusinessType.EXPORT)
    @GetMapping("/exportAttendance/export")
    public AjaxResult exportAttendanceWithCondition(AttendanceDailyRecord queryString) {
//        List<AttendanceDailyRecord> attendanceDailyRecords = workAttendanceService.listOfAttendanceRecordByIds(ids);
        List<AttendanceDailyRecord> attendanceDailyRecords = workAttendanceService.listOfAttendanceRecord(queryString);
        AttendanceDailyRecord attendanceDailyRecord = attendanceDailyRecords.get(Constant.NUMBER_0);
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName("考勤记录");
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, AttendanceDailyRecord.class, attendanceDailyRecords);
//        String fileName = attendanceDailyRecord.getDeptName().concat(attendanceDailyRecord.getWorkTime()) + ".xlsx";
        String fileName = attendanceDailyRecord.getDeptName().concat(attendanceDailyRecord.getShiftName()) + ".xlsx";
        OutputStream out = null;
        try {
            out = new FileOutputStream(getAbsoluteFile(fileName));
            workbook.write(out);
            return AjaxResult.success(fileName);
        } catch (Exception e) {
            log.error("excel输出错误信息:[{}]", e.getCause(), e);
            AjaxResult.error();
        } finally {
            IOUtils.closeQuietly(workbook);
            IOUtils.closeQuietly(out);
        }
        return AjaxResult.success();
    }

    public String getAbsoluteFile(String filename) {
        String downloadPath = RuoYiConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }

    /**
     * @param attendanceSumDailyRecord
     * @return com.ruoyi.common.core.page.TableDataInfo
     * @Description : 月考勤信息汇总
     * @Author : leizhang
     * @Date 4:08 下午 2021/11/21
     **/
    @GetMapping("/getAttendanceSumMonthRecord")
    @Log(title = "月考勤信息汇总", businessType = BusinessType.INSERT)
    public TableDataInfo getAttendanceSumMonthRecord(AttendanceMonthSumRecord attendanceSumDailyRecord) {
        startPage();
        List<AttendanceMonthSumRecord> attendanceSumDailyRecords = workAttendanceService.listOfAttendanceSumReCord(attendanceSumDailyRecord);
        return getDataTable(attendanceSumDailyRecords);
    }

    /**
     * @param attendanceMonthRecord
     * @return com.ruoyi.common.core.page.TableDataInfo
     * @Description : 月考考勤个人信息
     * @Author : leizhang
     * @Date 4:08 下午 2021/11/21
     **/
    @GetMapping("/getAttendanceMonthRecord")
    @Log(title = "月考勤信息详情", businessType = BusinessType.INSERT)
    public TableDataInfo getAttendanceMonthRecord(AttendanceMonthRecord attendanceMonthRecord)throws Exception{
        startPage();
        List<AttendanceMonthRecord> attendanceSumDailyRecords = workAttendanceService.listOfAttendanceMonthRecord(attendanceMonthRecord);
        return getDataTable(attendanceSumDailyRecords);
    }

    @GetMapping("/getAttendanceMonthRecordByIdCard")
    @Log(title = "月考勤信息详情个人", businessType = BusinessType.INSERT)
    public TableDataInfo getAttendanceMonthRecordByIdCard(AttendanceDailyRecord attendanceDailyRecord) {
        startPage();
        List<AttendanceDailyRecord> list = workAttendanceService.listOfAttendanceRecordByIdCard(attendanceDailyRecord);
        return getDataTable(list);
    }

    /**
     * @param attendanceDailyRecord
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @Description : 月考勤记录导出
     * @Author : leizhang
     * @Date 2:19 下午 2021/11/25
     **/
    @Log(title = "月考勤记录导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exportAttendanceMonth")
    public AjaxResult exportAttendanceIngo( AttendanceDailyRecord attendanceDailyRecord) {
        Map<String, Object> resultMap = workAttendanceService.listOfAttendanceRecordVo(attendanceDailyRecord);
        List<ExcelExportEntity> colList = Lists.newArrayList();
        Set<String> headTitle = (Set<String>) resultMap.get("headTitle");
        //拼接excel表格
        ExcelExportEntity colEntity = new ExcelExportEntity("姓名", "staffName");
        colEntity.setNeedMerge(true);
        colList.add(colEntity);
        //身份证号
        colEntity = new ExcelExportEntity("身份证", "idCard");
        colEntity.setNeedMerge(true);
        colList.add(colEntity);

        //身份证号
        colEntity = new ExcelExportEntity("岗位", "postName");
        colEntity.setNeedMerge(true);
        colList.add(colEntity);

        ExcelExportEntity dateGroup = new ExcelExportEntity("考勤日期", "date");
        List<ExcelExportEntity> deliColList = Lists.newArrayList();
        for (String s : headTitle) {
            deliColList.add(new ExcelExportEntity(s, s));
        }
        dateGroup.setList(deliColList);
        colList.add(dateGroup);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<AttendanceMonthRecordVo> listData = (List<AttendanceMonthRecordVo>) resultMap.get("data");
        for (AttendanceMonthRecordVo data : listData) {
            Map<String, Object> valMap = new HashMap<String, Object>();
            valMap.put("staffName", data.getStaffName());
            valMap.put("idCard", data.getIdCard());
            valMap.put("postName", data.getPostName());
            List<AttendanceMonthRecordDto> attendanceMonthRecordDtoList = data.getAttendanceMonthRecordDtoList();
            List<Map<String, Object>> deliDetailList = new ArrayList<Map<String, Object>>();
            for (AttendanceMonthRecordDto attendanceMonthRecordDto : attendanceMonthRecordDtoList) {
                Map<String, Object> deliValMap = new HashMap<String, Object>();
                deliValMap.put(attendanceMonthRecordDto.getWorkTime(), attendanceMonthRecordDto.getAttendanceValue());
                deliDetailList.add(deliValMap);
            }
            valMap.put("date", deliDetailList);
            list.add(valMap);
        }
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName("考勤记录");
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, colList, list);
        String fileName = "考勤记录".concat("_") + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()).toString() + ".xlsx";
        OutputStream out = null;
        try {
            out = new FileOutputStream(getAbsoluteFile(fileName));
            workbook.write(out);
            return AjaxResult.success(fileName);
        } catch (Exception e) {
            log.error("excel输出错误信息:[{}]", e.getCause(), e);
            AjaxResult.error();
        } finally {
            IOUtils.closeQuietly(workbook);
            IOUtils.closeQuietly(out);
        }
        return AjaxResult.success();
    }
}
